<template>
  <div class="bg-white textHeight redStar">
    <div>
      <van-form @submit="onSubmit">
        <!-- 企业名称 -->
        <van-field
          readonly
          clickable
          name="companyId"
          :value="formInline.companyName"
          label="企业名称"
          placeholder="请选择企业名称"
          :rules="[{ required: true, message: '请选择企业名称' }]"
          @click="showPicker1 = true"
        />
        <van-popup v-model="showPicker1" position="bottom" get-container="body">
          <van-search v-model="positionSearch" placeholder="请输入企业名称" @clear="searchClear" @search="onSearch2(positionSearch)" @change="onSearch2(positionSearch)" />
          <span v-if="retColumns.length > 0">
            <van-picker
              show-toolbar
              :columns="retColumns"
              @confirm="onConfirm1"
              @cancel="columnsCancel"
            />
          </span>
          <span v-else>
            <van-picker
              show-toolbar
              :columns="columns1"
              @confirm="onConfirm1"
              @cancel="columnsCancel"
            />
          </span>
        </van-popup>
        <!-- 隐患来源 -->
        <van-field
          readonly
          clickable
          name="checkSource"
          :value="formInline.checkSource.text"
          label="隐患来源"
          placeholder="点击选择隐患来源"
          :rules="[{ required: true, message: '请选择隐患来源' }]"
          @click="showPickerCheckSource = true"
        />
        <van-popup v-model="showPickerCheckSource" position="bottom" :lock-scroll="true" get-container="body">
          <van-picker
            show-toolbar
            :columns="[{label:'集团录入',text:'集团录入',value:'3'},{label:'外部单位检查',text:'外部单位检查',value:'4'},{label:'其他',text:'其他',value:'5'}]"
            :style="{height: '20%'}"
            @confirm="onConfirmCheckSource"
            @cancel="showPickerCheckSource = false"
          />
        </van-popup>
        <!-- 隐患描述 -->
        <van-field
          v-model="formInline.describe"
          rows="3"
          name="describe"
          autosize
          label="隐患描述"
          type="textarea"
          maxlength="500"
          placeholder="请输入隐患描述"
          show-word-limit
          :rules="[{ required: true, message: '请输入隐患描述' }]"
        />
        <!-- 隐患位置 -->
        <van-field
          v-model="formInline.position"
          maxlength="30"
          name="position"
          label="隐患位置"
          placeholder="请输入隐患位置"
          :rules="[{ required: true, message: '请输入隐患位置' }]"
        />
        <!-- 隐患等级 -->
        <van-field
          readonly
          clickable
          name="dangersLevel"
          :value="formInline.dangersLevel.text"
          label="隐患等级"
          placeholder="点击选择隐患等级"
          :rules="[{ required: true, message: '请选择隐患等级' }]"
          @click="showPicker2 = true"
        />
        <van-popup v-model="showPicker2" position="bottom" :lock-scroll="true" get-container="body">
          <van-picker
            show-toolbar
            :columns="selectOptionAll['环保-隐患等级']"
            :style="{height: '20%'}"
            @confirm="onConfirm2"
            @cancel="showPicker2 = false"
          />
        </van-popup>
        <!-- 隐患类别 -->
        <van-field
          readonly
          clickable
          name="dangersType"
          :value="formInline.dangersType.text"
          label="隐患类别"
          placeholder="点击选择隐患类别"
          :rules="[{ required: true, message: '请选择隐患类别' }]"
          @click="showPicker3 = true"
        />
        <van-popup v-model="showPicker3" position="bottom" get-container="body">
          <van-picker
            show-toolbar
            :columns="selectOptionAll[dangersTypeList[$route.query.current]]"
            @confirm="onConfirm3"
            @cancel="showPicker3 = false"
          />
        </van-popup>
        <!-- 检查依据 -->
        <van-field
          v-model="formInline.checkBasis"
          name="checkBasis"
          maxlength="30"
          label="检查依据"
          placeholder="请输入检查依据"
          :rules="[{ required: true, message: '请输入检查依据' }]"
        />
        <!-- 检查人员 -->
        <van-field
          v-model="formInline.checkPerson"
          name="checkPerson"
          maxlength="10"
          label="检查人员"
          placeholder="请输入检查人员"
          :rules="[{ required: true, message: '请输入检查人员' }]"
        />
        <!-- 检查时间 -->
        <van-field
          readonly
          clickable
          name="checkTime"
          :value="formInline.checkTime"
          label="检查时间"
          placeholder="点击选择检查时间"
          :rules="[{ required: true, message: '请选择检查时间' }]"
          @click="showPicker4 = true"
        />
        <van-field
          readonly
          clickable
          name="deadline"
          :value="formInline.deadline"
          label="整改期限"
          placeholder="点击选择整改期限"
          :rules="[{ required: true, message: '请选整改期限' }]"
          @click="showPicker5 = true"
        />
        <van-popup v-model="showPicker4" position="bottom" get-container="body">
          <!--        :max-date="maxDate"-->
          <van-datetime-picker
            v-model="defaultCheckTime"
            type="date"
            title="选择检查时间"
            :min-date="minDate"
            :max-date="maxDate"
            @confirm="onConfirm4"
            @cancel="showPicker4 = false"
          />
        </van-popup>
        <van-popup v-model="showPicker5" position="bottom" get-container="body">
          <!--        :max-date="maxDate"-->
          <van-datetime-picker
            v-model="defaultCheckTime"
            type="date"
            title="选择检查时间"
            :min-date="minDate1"
            @confirm="onConfirm5"
            @cancel="showPicker5 = false"
          />
        </van-popup>
        <van-field name="dangersPicture" label="隐患图片" class="notRedStar" :rules="[{ required: false, message: '请上传隐患图片' }]">
          <template #input>
            <div>
              <div>
                <van-uploader ref="uploader" v-model="dangersPicture" :after-read="uploadFile" :max-count="10" @delete="deleteFile" />
              </div>
              <div style="color:red;font-size: 12px">只能上传png/jpg/jpeg/gif文件，且不超过5MB，限制最多上传10个文件。</div>
            </div>
          </template>
        </van-field>
        <div style="margin: 16px;padding-bottom: 16px">
          <van-button :loading="butLoading" :loading-text="loadingText" round block type="info" native-type="submit">提交</van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>
<script>
import commonList from '@/assets/mixin/commonList'
import { parseTime, timeFormatter } from '@/utils'
import { addAttachment, addDangersLedger, HbAddDangersLedger, XfAddDangersLedger, NyAddDangersLedger } from '@/api/commonPage/dangerTreatment'
import { Toast } from 'vant'

export default {

  mixins: [commonList],
  data() {
    return {
      timeFormatter: timeFormatter,
      defaultCheckTime: new Date(),
      formInline: {
        dangersLevel: {},
        checkSource: {},
        dangersType: {},
        checkTime: parseTime(new Date(), '{y}-{m}-{d}'),
        deadline: parseTime(new Date(), '{y}-{m}-{d}'),
        checkBasis: '',
        checkPerson: '',
        companyId: '',
        describe: '',
        position: '',
        dangersPicture: []
      },
      dangersPicture: [],
      showPicker1: false,
      showPicker2: false,
      showPicker3: false,
      showPicker4: false,
      showPicker5: false,
      showPickerCheckSource: false,
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(),
      minDate1: new Date(),
      columns1: [],
      retColumns: [],
      dangersTypeList: {
        安全生产: '安全-隐患类别',
        环保管理: '环保-隐患类别',
        消防管理: '消防-隐患类别',
        能源管理: '能源-隐患类别'
      },
      apiMap: {
        安全生产: addDangersLedger,
        环保管理: HbAddDangersLedger,
        消防管理: XfAddDangersLedger,
        能源管理: NyAddDangersLedger

      },
      positionSearch: '',
      butLoading: false,
      loadingText: ''
    }
  },
  mounted() {
    this.columns1 = this.$store.state['app']['companyList'].map(v => v.organizationName)
  },
  methods: {
    async onSubmit() {
      this.butLoading = true
      this.loadingText = '提交中，请稍候'
      const obj = {
        checkSource: this.formInline.checkSource.value,
        dangersLevel: this.formInline.dangersLevel.value,
        dangersType: this.formInline.dangersType.value,
        checkTime: this.formInline.checkTime,
        deadline: this.formInline.deadline,
        checkBasis: this.formInline.checkBasis,
        checkPerson: this.formInline.checkPerson,
        companyId: this.formInline.companyId,
        describe: this.formInline.describe,
        position: this.formInline.position,
        dangersPicture: this.formInline.dangersPicture.join(',')
      }
      const { msg, status } = await this.apiMap[this.$route.query.current](obj)
      if (msg && status === 0) {
        this.butLoading = false
        this.$emit('input', false)
        this.$emit('flushed', false)
        Toast(msg)
      }
    },
    onConfirm1(item) {
      this.formInline.companyName = item
      this.formInline.companyId = this.$store.state['app']['companyList'].find(val => val.organizationName === item)?.organizationId
      this.showPicker1 = false
      this.retColumns = []
      this.positionSearch = ''
    },
    onConfirm2(item) {
      this.formInline.dangersLevel = item
      this.showPicker2 = false
    },
    onConfirm3(item) {
      this.formInline.dangersType = item
      this.showPicker3 = false
    },
    onConfirm4(item) {
      this.formInline.checkTime = parseTime(new Date(item), '{y}-{m}-{d}')
      this.showPicker4 = false
    },
    onConfirm5(item) {
      this.formInline.deadline = parseTime(new Date(item), '{y}-{m}-{d}')
      this.showPicker5 = false
    },
    onConfirmCheckSource(item) {
      this.formInline.checkSource = item
      this.showPickerCheckSource = false
    },
    uploadFile(file) {
      this.butLoading = true
      this.loadingText = '图片正在上传中，请稍候'
      file.status = 'uploading'
      file.message = '上传中...'
      const formData = new FormData()
      formData.append('file', file.file)
      formData.append('attachName', file.file.name)
      formData.append('attachDesc', file.file.name)
      addAttachment(formData).then(res => {
        if (res.status === 0 && res.data) {
          file.status = ''
          file.message = ''
          this.formInline.dangersPicture.push(res.data.attachId)
          this.butLoading = false
        } else {
          file.status = 'failed'
          file.message = '上传失败'
        }
      }).catch(() => {
        file.status = 'failed'
        file.message = '上传失败'
        this.butLoading = false
      })
    },
    deleteFile(info, { index }) {
      this.formInline.dangersPicture.splice(index, 1)
    },
    onSearch2(val) {
      const retColumns = []
      this.columns1.forEach((item) => {
        if (item.indexOf(val) > -1) {
          retColumns.push(item)
        }
      })
      this.retColumns = retColumns
    },
    searchClear() {
      this.retColumns = []
    },
    columnsCancel() {
      this.showPicker1 = false
      this.retColumns = []
      this.positionSearch = ''
    }
  }
}
</script>
<style scoped lang="scss">
.textHeight {
  min-height: 90vh;
}
::v-deep .van-field__body {
  input::placeholder {
    color: #909399;
  }
  textarea::placeholder {
    color: #909399;
  }
}
.redStar ::v-deep .van-field__label::before{
  content: "*";
  color: red;
  margin-right: 3px;
}
.redStar ::v-deep .van-field {
&.notRedStar .van-field__label::before{
  content: "";
  padding-right: 5px;
}

}
</style>
